using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace GameOverlayWPF
{
    /// <summary>
    /// 方案使用次数管理服务
    /// </summary>
    public class SchemeUsageService
    {
        private static SchemeUsageService? _instance;
        private static readonly HttpClient Http = new HttpClient
        {
            Timeout = TimeSpan.FromSeconds(10)
        };

        private const string ApiBase = "https://www.maqt.top";
        private const string ApiReferer = "https://www.maqt.top/";

        public static SchemeUsageService Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new SchemeUsageService();
                }
                return _instance;
            }
        }

        private SchemeUsageService()
        {
        }

        /// <summary>
        /// 增加方案使用次数
        /// </summary>
        /// <param name="schemeId">方案ID</param>
        /// <param name="isAobMode">是否为全面战场模式</param>
        /// <returns>使用次数增加结果</returns>
        public async Task<SchemeUsageResult> IncreaseUsageAsync(int schemeId, bool isAobMode)
        {
            // 使用CancellationToken确保超时控制
            using (var cts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10)))
            {
                try
                {
                    // 根据模式选择API端点
                    string endpoint = isAobMode ? "/api/schemes_aob" : "/api/schemes";
                    string url = $"{ApiBase}{endpoint}/{schemeId}/use";

                    System.Diagnostics.Debug.WriteLine($"调用使用次数API: {url}");

                    using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                    {
                        request.Headers.Referrer = new Uri(ApiReferer);
                        
                        var response = await Http.SendAsync(request, cts.Token);
                        var body = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine($"API响应状态: {response.StatusCode}");
                    System.Diagnostics.Debug.WriteLine($"API响应内容: {body}");

                    if (response.IsSuccessStatusCode)
                    {
                        var result = JsonConvert.DeserializeObject<ApiResponse>(body);
                        if (result?.Success == true && result.Data != null)
                        {
                            return new SchemeUsageResult
                            {
                                Success = true,
                                Message = result.Message ?? "使用数增加成功",
                                SchemeUses = result.Data.SchemeUses,
                                GlobalTotalUses = result.Data.GlobalTotalUses
                            };
                        }
                    }
                    else if ((int)response.StatusCode == 429)
                    {
                        // 冷却期错误
                        var errorResult = JsonConvert.DeserializeObject<ErrorResponse>(body);
                        return new SchemeUsageResult
                        {
                            Success = false,
                            Message = errorResult?.Message ?? "您已在短时间内使用过此方案",
                            ErrorType = "cooldown",
                            CooldownMinutes = errorResult?.CooldownMinutes ?? 5
                        };
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        return new SchemeUsageResult
                        {
                            Success = false,
                            Message = "方案不存在",
                            ErrorType = "not_found"
                        };
                    }
                    else
                    {
                        return new SchemeUsageResult
                        {
                            Success = false,
                            Message = "服务器错误",
                            ErrorType = "server_error"
                        };
                    }
                }

                    return new SchemeUsageResult
                    {
                        Success = false,
                        Message = "未知错误"
                    };
                }
                catch (TaskCanceledException ex)
                {
                    System.Diagnostics.Debug.WriteLine($"请求超时: {ex.Message}");
                    return new SchemeUsageResult
                    {
                        Success = false,
                        Message = "请求超时，请稍后重试",
                        ErrorType = "timeout"
                    };
                }
                catch (HttpRequestException ex)
                {
                    System.Diagnostics.Debug.WriteLine($"网络请求失败: {ex.Message}");
                    return new SchemeUsageResult
                    {
                        Success = false,
                        Message = "网络连接失败，请检查网络",
                        ErrorType = "network"
                    };
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"增加使用次数失败: {ex.Message}");
                    System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                    return new SchemeUsageResult
                    {
                        Success = false,
                        Message = $"操作失败: {ex.Message}",
                        ErrorType = "unknown"
                    };
                }
            }
        }

        // API响应模型
        private class ApiResponse
        {
            [JsonProperty("success")]
            public bool Success { get; set; }

            [JsonProperty("message")]
            public string? Message { get; set; }

            [JsonProperty("data")]
            public ApiData? Data { get; set; }
        }

        private class ApiData
        {
            [JsonProperty("schemeUses")]
            public int SchemeUses { get; set; }

            [JsonProperty("globalTotalUses")]
            public int GlobalTotalUses { get; set; }
        }

        private class ErrorResponse
        {
            [JsonProperty("success")]
            public bool Success { get; set; }

            [JsonProperty("message")]
            public string? Message { get; set; }

            [JsonProperty("cooldownMinutes")]
            public int? CooldownMinutes { get; set; }
        }
    }

    /// <summary>
    /// 方案使用次数操作结果
    /// </summary>
    public class SchemeUsageResult
    {
        public bool Success { get; set; }
        public string Message { get; set; } = string.Empty;
        public string ErrorType { get; set; } = string.Empty;
        public int SchemeUses { get; set; }
        public int GlobalTotalUses { get; set; }
        public int CooldownMinutes { get; set; }
    }
}
